<template>
    <div>
        <el-form inline>
            <el-form-item label="名称">
                <el-input placeholder="角色名称" v-model="searchTempObj.roleName" />
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="searchTempObj.is_active" clearable  placeholder="请选择">
                    <el-option v-for="(item,index) in activeList" :key="index" :label="item.name" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button @click="clearSearch">清空</el-button>
        </el-form>

        <div style="margin-bottom: 20px">
            <el-button type="primary" v-if="addButtons" @click="addRole">添加</el-button>
        </div>

        <el-table border stripe :data="roleList" v-loading="listLoading" >

            <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="is_disable" label="是否启用">
                <template slot-scope="{row,$index}">
                    <el-switch v-model="row.is_active" :disabled="!editButtons" @change="changeStatus(row,$index)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column prop="desc" label="备注" />
            <el-table-column prop="create_time" label="创建时间" width="180" />
            <el-table-column prop="update_time" label="更新时间" width="180" />


            <el-table-column label="操作" width="300" align="center">
                <template slot-scope="{row}">
                    <HintButton size="mini" type="primary" icon="mi-icon-shuzhuangtu_o" title="分配权限" v-if="perButtons"  @click="settingRole(row)" />

                    <HintButton size="mini" type="primary" icon="el-icon-edit" title="修改角色" v-if="editButtons" @click="updateRole(row)" />


                    <HintButton size="mini" type="danger" icon="el-icon-delete" title="删除角色" v-if="delButtons" @click="removeRole(row)" />
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination :current-page="page" :total="total" :page-size="limit" :page-sizes="limitArr" :pager-count="pagerCount"
            @current-change="getData" @size-change="handleSizeChange" style="padding: 20px 0;"
            layout="prev, pager, next, jumper, ->, sizes, total" />

            <el-dialog title="重置密码" :visible.sync="dialogRole" :before-close="clearRoleData">
            <el-form :model="roleInfo" :rules="rules" ref="roleForm" label-width="80px">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="roleInfo.name"></el-input>
                </el-form-item>
                <el-form-item label="是否启用" prop="is_active">
                    <el-radio-group v-model="roleInfo.is_active">
                        <el-radio v-for="(item, index) in activeList" :key="index" :label="item['value']">{{item['name']}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="desc">
                    <el-input v-model="roleInfo.desc" type="textarea" :row="2"  />
                </el-form-item>
                
            </el-form>

            <div slot="footer">
                <el-button @click="clearRoleData">取 消</el-button>
                <el-button :loading="buttonLoading" type="primary" @click="saveRole">确 定</el-button>
                
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {

        name: 'RoleList',

        data() {
            var validateName = (rule, value, callback) => {

                const regex = /^[\u4E00-\u9FA5\uF900-\uFA2D]{2,15}$/

                if (!value || !value.trim()) {
                    return callback(new Error('名称不能为空'));
                }else if (!regex.test(value)) {
                    return callback(new Error('角色名称只能是中文是2到15位'));
                }else{
                    callback()
                }
            }
            return {
                total: 0, // 总记录数
                page: 1, // 当前页码
                limit: this.$util.page.limit, // 每页记录数
                limitArr:this.$util.page.size,
                pagerCount:this.$util.page.pagerCount,
                activeList:this.$util.activeList,
                roleList: [],
                roleInfo: {},
                // 搜索提交
                searchObj: {
                    name: '',
                    enabled:'',
                },
                
                // 搜索临时存储
                searchTempObj: {
                    name: '',
                    enabled:'',
                },

                // 数据列表加载
                listLoading:true,

                dialogRole:false,
                // 按钮加载状态
                buttonLoading: true,

                rules:{
                    name:[{ validator: validateName, trigger: 'blur' }]
                },

            }
        },
        computed:{
            addButtons(){
                return this.$util.isButton('system.role.add')
            },
            editButtons(){
                return this.$util.isButton('system.role.edit')
            },
            delButtons(){
                return this.$util.isButton('system.role.delete')
            },
            perButtons(){
                return this.$util.isButton('system.role.permission')
            },
        },
        mounted() {
            this.getData()
        },

        methods: {
            async getData(pager = 1) {
                this.listLoading = true
                this.page = pager
                let {
                    page,
                    limit,
                    searchObj
                } = this
                let result = await this.$API.role.reqRoleList({page,limit,...searchObj})
                if (result.code = 200) {
                    this.roleList = result.data.items.filter(item => {
                        item.edit = false
                        return item
                    })
                    this.total = result.data.total
                    this.listLoading = false
                }
            },
            // 设置条数
            handleSizeChange(event) {
                this.limit = event
                this.getData()
            },
            // 搜索
            search() {
                // 深拷贝
                this.searchObj = {
                    ...this.searchTempObj
                }
                this.getData()
            },
            // 清空搜索
            clearSearch() {
                this.searchObj = this.searchTempObj = {}
                this.getData()
            },


            // 添加角色
            addRole() {
                this.dialogRole = true;
                this.buttonLoading = false;
                this.roleInfo = {
                    is_active:true,
                }

                

            },
            // 更新角色
            async updateRole(row) {
                this.dialogRole = true;
                this.buttonLoading = false;
                let result = await this.$API.role.reqRoleInfo(row.id);
                if (result.code == 200) {
                    this.roleInfo = result.data
                    
                }
            },
            saveRole(){
                this.buttonLoading = true;
                let {roleInfo,page} = this;
                this.$refs.roleForm.validate(async (valid) => {
                    if (valid) {
                        let result = await this.$API.role.reqAddOrUpdateRole(roleInfo)
                        if (result.code == 201 || result.code == 200) {
                            this.$message({
                                type: 'success',
                                message: roleInfo.id ? '修改成功' : '添加成功'
                            })
                            this.getData(roleInfo.id ? page : 1)
                            this.clearRoleData()
                        }
                        this.buttonLoading = false;
                    }else{
                        this.$message({
                            type: "error",
                            message: roleInfo.id ? '修改失败' : '添加失败'
                        })
                        this.buttonLoading = false;
                        return false;
                    }
                })
                
            },
            clearRoleData(){
                this.dialogRole = false;
                this.roleInfo = {}
                // 清空上一次的验证规则
                this.$nextTick(() => this.$refs.roleForm.clearValidate())
            },
            // 删除单个角色
            removeRole(row) {

                this.$confirm(`此操作将永久删除${row.name}该数据, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let result = await this.$API.role.reqRemoveRole(row.id)
                    if (result.code = 204) {
                        this.$message({
                            type: 'success',
                            message: `删除${row.name}成功！`
                        })
                        this.getData(this.roleList.length > 1 ? this.page : this.page - 1)
                    }

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: `已取消删除${row.name}！`
                    });
                });
            },
            settingRole(row){
                this.$router.push(`/system/role/auth/${row.id}`)
            },
            async changeStatus(row,index){
                let roleInfo = {
                    id:row.id,
                    is_active:row.is_active
                }
                let result = await this.$API.role.reqAddOrUpdateRole(roleInfo)
                if (result.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '修改成功'
                    })

                }
            }

        }
    }
</script>

<style scoped>
    .edit-input {
        padding-right: 100px;
    }

    .cancel-btn {
        position: absolute;
        right: 15px;
        top: 10px;
    }
</style>